package gitee_sdk

import (
	"devops/pkg/git/git_model"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

type giteeClient struct {
	g     *http.Client
	token string
}

func NewGiteeClient(token string) *giteeClient {
	return &giteeClient{g: &http.Client{}, token: token}
}

func (gitee *giteeClient) GetRepos() ([]git_model.Repo, error) {
	endpoint := fmt.Sprintf("https://gitee.com/api/v5/user/repos?access_token=%s&sort=full_name", gitee.token)
	resp, err := gitee.g.Get(endpoint)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("连接失败")
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	repos := make([]git_model.Repo, 0)
	json.Unmarshal(body, &repos)
	for i, r := range repos {
		// modify other api data
		repos[i].CloneUrl = r.HtmlUrl
	}
	return repos, nil
}

func (gitee *giteeClient) GetBranches(owner string, repo string) []git_model.Branch {
	endpoint := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/branches?access_token=%s", owner, repo, gitee.token)
	resp, err := gitee.g.Get(endpoint)
	if err != nil {
		return nil
	}
	if resp.StatusCode != 200 {
		return nil
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	branches := make([]git_model.Branch, 0)
	json.Unmarshal(body, &branches)
	// 获取分支提交时间
	for i, b := range branches {
		api := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/branches/%s?access_token=%s", owner, repo, b.Name, gitee.token)
		var date string
		if resp, err := gitee.g.Get(api); err != nil {
			date = "-"
		} else {
			body, _ := ioutil.ReadAll(resp.Body)
			b := Branch{}
			json.Unmarshal(body, &b)
			date = git_model.CommittedDate(&b.Commit.Commit.Committer.Date)
		}
		branches[i].CommittedDate = date
	}
	return branches
}
